<template>
  <div class="pagination">
    <a
      href="#"
      class="prev-btn"
      @click.prevent="handleClick(curIdx - 1)"
    >
      上一页
    </a>
    <a
      href="#"
      :class="['page-num',{current: page === curIdx}]"
      v-for="page in pages" :key="page"
      @click.prevent="handleClick(page)"
    >
      {{page}}
    </a>
    <a
      href="#"
      class="prev-btn"
      @click.prevent="handleClick(curIdx + 1)"
    >
      下一页
    </a>
    <span>共<strong>{{pagesCount}}</strong>页</span>
  </div>
</template>

<script lang="ts">
  import { defineComponent, ref, watch } from 'vue'
  export default defineComponent({
    props: {
      count: {
        type: Number,
        required: true
      },
      curIdx: {
        type: Number,
        required: true
      }
    },
    emits: ["changePage"],
    setup (props, { emit }) {
      const pages = ref<number[]>([])
      const pagesCount = Math.ceil(props.count / 10)
      // const length = Math.min(5, pagesCount)
      const changePages = () => {
        const a = Math.ceil(props.curIdx / 5)
        let start = (a-1) * 5 + 1
        let end = a * 5 > pagesCount?pagesCount:(a*5)
        pages.value = []
        for(let i = start; i <= end; i ++) {
          pages.value.push(i)
        }
      }
      changePages()

      watch(() => props.curIdx, () => changePages())

      const handleClick = (page: number) => {
        if (page < 1 || page > pagesCount) return
        emit('changePage', page)
      }
      return {
        pages,
        handleClick,
        pagesCount
      }
    }
  })
</script>

<style lang="scss" scoped>
  .pagination {
    text-align: center;
    color: #999999;
    padding: 20px 20px 40px 0;
    a,span {
      display: inline-block;
      color: #999999;
    }
    .current {
      background-color: #1ABC9C;
      color: white;
    }
    .page-num {
      width: 40px;
      height: 40px;
      margin: 0 5px;
      line-height: 40px;
      border-radius: 3px;
    }
    .next-btn {
      margin: 0 5px;
    }
    .prev-btn,
    .next-btn {
      width: 88px;
      height: 42px;
      line-height: 42px;
      color: #666;
      border-radius: 3px;
      background-color: white;
    }
    .page-input {
      width: 50px;
      height: 42px;
      margin: 0 5px;
      border: 1px solid #E6E6E6;
      border-radius: 3px;
      color: #666;
      text-align: center;
    }
    .input {
      margin-left: 10px;
    }
    .confirm-btn {
      width: 48px;
      height: 32px;
      margin-left: 10px;
      border: 1px solid #E6E6E6;
      border-radius: 3px;
      line-height: 32px;
      color: #666;
      cursor: pointer;
    }
  }
</style>